//
//  MineViewController.m
//  Double
//
//  Created by 袁庆秋 on 15/5/21.
//  Copyright (c) 2015年 袁庆秋. All rights reserved.
//

#import "MineViewController.h"
#import "MineTableViewCell.h"
#import "Mine.h"
#import "AboutUsViewController.h"
#import "HHAlertView.h"
#import "HistoryViewController.h"
#import "CollectViewController.h"
#import <UIImageView+WebCache.h>
#import <AFNetworking.h>
#import "WeiboSDK.h"
#import "AppDelegate.h"


@interface MineViewController ()<UITableViewDataSource, UITableViewDelegate,UIImagePickerControllerDelegate, WBHttpRequestDelegate>
@end

#define kAppKey         @"1837158850"
#define kRedirectURI    @"http://www.sharesdk.cn"

@implementation MineViewController

- (void)dealloc
{
    [_fiels release];
    [_button1 release];
    [_headerImageView release];
    [_array release];
    [_userDic release];
    [super dealloc];
}
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.array = [[NSMutableArray alloc]init];
        self.userDic = [NSMutableDictionary dictionary];
        self.fiels = [NSArray array];
        NSString * path = [[NSBundle mainBundle]pathForResource:@"Mine" ofType:@"plist"];
        NSMutableArray * myArray = [NSMutableArray arrayWithContentsOfFile:path];
        for (NSDictionary * dic in myArray) {
            Mine * model = [[Mine alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            [self.array addObject:model];
            [model release];
        }
    }
    return self;
}
- (void)loadView
{
    [super loadView];
    self.navigationController.navigationBar.translucent = NO;
    [self createImageView];
    [self createView];

    

    
}








- (void)viewDidLoad {
    [super viewDidLoad];
}

//接收消息
- (void)receiveMessage:(NSNotification *)noti
{
    NSDictionary *dic = noti.userInfo;
    NSString *imageName = [dic objectForKey:@"profile_image_url"];
    [self.headerImageView sd_setImageWithURL:[NSURL URLWithString:imageName] placeholderImage:[UIImage imageNamed:@"wode.png"] options:SDWebImageRetryFailed];
    self.nameLabel.text = [dic objectForKey:@"name"];
    [self.tableView reloadData];
}


//创建头像view
- (void)createImageView
{
    UIImageView *groundView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 160)];
    groundView.image = [UIImage imageNamed:@"d.jpg"];
    groundView.userInteractionEnabled = YES;
    [self.view addSubview:groundView];
    
    self.headerImageView = [[UIImageView alloc] initWithFrame:CGRectMake((self.view.frame.size.width - 100) / 2, 20, 100, 100)];
    self.headerImageView.layer.cornerRadius = 50;
    self.headerImageView.clipsToBounds = YES;
    
    //注册消息中心
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveMessage:) name:@"userInformation" object:nil];
    
    
    
    
    self.headerImageView.image = [UIImage imageNamed:@"renwu.png"];
    self.headerImageView.userInteractionEnabled = YES;
    
    UITapGestureRecognizer *imageTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    [self.headerImageView addGestureRecognizer:imageTap];

    [groundView addSubview:self.headerImageView];
    
    self.nameLabel = [[UILabel alloc] initWithFrame:CGRectMake((self.view.frame.size.width - 100) / 2, 130, 100, 20)];
    self.nameLabel.textAlignment = NSTextAlignmentCenter;
    self.nameLabel.font = [UIFont systemFontOfSize:15];
    self.nameLabel.textColor = [UIColor whiteColor];
    self.nameLabel.text = @"未登录";
    [groundView addSubview:self.nameLabel];
    [groundView release];
    [self.headerImageView release];
    [self.nameLabel release];
}


//点击图片登录
- (void)tapAction:(UITapGestureRecognizer *)tap
{
    WBAuthorizeRequest *request = [WBAuthorizeRequest request];
    request.redirectURI = kRedirectURI;
    request.scope = @"all";
    request.userInfo = @{@"SSO_From": @"SendMessageToWeiboViewController",
                         @"Other_Info_1": [NSNumber numberWithInt:123],
                         @"Other_Info_2": @[@"obj1", @"obj2"],
                         @"Other_Info_3": @{@"key1": @"obj1", @"key2": @"obj2"}};
    [WeiboSDK sendRequest:request];
    [self.tableView reloadData];
}


- (void)createView
{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 160, self.view.frame.size.width, self.view.frame.size.height - 64 - 160 - 49) style:UITableViewStylePlain];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.view addSubview:self.tableView];
    [self.tableView release];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
       return 50;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSUserDefaults *myLoginID = [NSUserDefaults standardUserDefaults];
    NSString *uid = [myLoginID objectForKey:@"state"];
    if ([uid isEqualToString:@"登录"] ) {
        
        return self.array.count;
    } else
    return self.array.count - 1;
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * cellInde = @"cell";
    
        MineTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellInde];
        if (!cell) {
            cell = [[[MineTableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellInde]autorelease];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        Mine * model = [self.array objectAtIndex:indexPath.row];
        [cell.MyType setText:model.My];
        [cell.Image setImage:[UIImage imageNamed:model.MyImage]];
        return cell;
    return nil;
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark 每行cell点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0)
    {
        HistoryViewController * History = [[HistoryViewController alloc]init];
        History.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:History animated:YES];
        [History release];

    } else if (indexPath.row == 1)
    {
        CollectViewController * Collect = [[CollectViewController alloc]init];
        Collect.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:Collect animated:YES];
        [Collect release];

    } else if (indexPath.row == 2)
    {
        //清除缓存

        NSFileManager *manager = [NSFileManager defaultManager];
        NSArray *array = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
        NSString *path = [array lastObject];
        path = [NSString stringWithFormat:@"%@/Caches", path];
        NSLog(@"%@",path);
        BOOL judge = [manager fileExistsAtPath:path];
        if (judge) {
            [manager removeItemAtPath:path error:nil];

            [HHAlertView showAlertWithStyle:HHAlertStyleOk inView:self.view Title:@"Success" detail:@"清除缓存成功!" cancelButton:nil Okbutton:@"Sure" block:^(HHAlertButton buttonindex) {
                if (buttonindex == HHAlertButtonOk) {
                    NSLog(@"ok Button is seleced use block");
                }
                else
                {
                    NSLog(@"cancel Button is seleced use block");
                }
            }];
        }
        if (!judge) {
            [HHAlertView showAlertWithStyle:HHAlertStyleWraning inView:self.view Title:@"Wraing" detail:@"缓存为空" cancelButton:nil Okbutton:@"Sure"];
            
        }
        
        
    } else if (indexPath.row == 3)
    {
         [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"itms-apps://itunes.apple.com/cn/app/jie-zou-da-shi/id493901993?mt=8"]];

    } else if (indexPath.row == 4)
    {

        AboutUsViewController *about = [[AboutUsViewController alloc] init];
        about.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:about animated:YES];
        [about release];
    } else if (indexPath.row == 5) {
        
        //注销用户
        
        NSUserDefaults *myLoginID = [NSUserDefaults standardUserDefaults];
        NSString *state = [myLoginID objectForKey:@"state"];
        
        if ([state isEqualToString:@"登录"]) {
            
            NSLog(@"------------");
            AppDelegate *myDelegate =(AppDelegate*)[[UIApplication sharedApplication] delegate];
            [WeiboSDK logOutWithToken:myDelegate.wbtoken delegate:self withTag:@"user1"];
            [self.tableView reloadData];
            
        } else {
            [HHAlertView showAlertWithStyle:HHAlertStyleWraning inView:self.view Title:@"Wraing" detail:@"您还没有登陆哦" cancelButton:nil Okbutton:@"Sure"];
        }
    }
}

#pragma mark -
#pragma WBHttpRequestDelegate  注销用户事件

//切断软件和微博的联系
- (void)request:(WBHttpRequest *)request didFinishLoadingWithResult:(NSString *)result
{
    
    self.headerImageView.image = [UIImage imageNamed:@"renwu.png"];
    self.nameLabel.text = @"用户名";
    
    NSString *userId = nil;
    [[NSUserDefaults standardUserDefaults] setObject:userId forKey:@"loginName"];
    [[NSUserDefaults standardUserDefaults] setObject:@"注销" forKey:@"state"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    [HHAlertView showAlertWithStyle:HHAlertStyleOk inView:self.view Title:@"Success" detail:@"注销成功!" cancelButton:nil Okbutton:@"Sure" block:^(HHAlertButton buttonindex) {
        if (buttonindex == HHAlertButtonOk) {
            NSLog(@"ok Button is seleced use block");
        }
        else
        {
            NSLog(@"cancel Button is seleced use block");
        }
    }];
    [self.tableView reloadData];
}

//如果网络出现异常
- (void)request:(WBHttpRequest *)request didFailWithError:(NSError *)error;
{
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"网络异常" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alert show];
    [alert release];
    
}

- (void)clearCacheSuccess
{
    
}

@end
